<template>
  <div class="app-layout">
    <div class="sidebar">
      <div class="logo-section">
        <img src="/OIP.webp" alt="小智(医疗版)" width="160" height="160" class="rounded-full object-cover" />
        <span class="logo-text">小智(医疗版)</span>
      </div>
      
      <div class="sidebar-tabs">
        <el-tabs v-model="activeTab" class="sidebar-tab-container">
          <el-tab-pane label="会话" name="chat">
            <el-button class="new-chat-button" @click="newChat">
              <i class="fa-solid fa-plus"></i>
              &nbsp;新会话
            </el-button>
            <SessionList 
              ref="sessionListRef"
              :currentSessionId="currentSessionId"
              @loadSession="handleLoadSession"
            />
          </el-tab-pane>
          <el-tab-pane label="设置" name="settings">
            <PersonalSettings 
              ref="personalSettingsRef"
              @settingsChange="handleSettingsChange"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="main-content">
      <div class="chat-container">
        <!-- 顶部导航栏 -->
        <div class="chat-header">
          <div class="header-left">
            <el-button 
              type="text" 
              @click="$router.back()" 
              class="back-button"
            >
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <div class="doctor-avatar">
              <el-icon size="32" class="doctor-icon"><User /></el-icon>
            </div>
            <div class="doctor-info">
              <h3>小智医生</h3>
              <span 
                :class="[
                  'status', 
                  connectionStatus === 'connected' ? 'online' : 
                  connectionStatus === 'reconnecting' ? 'reconnecting' : 'offline'
                ]"
              >
                <i 
                  :class="[
                    'fa-solid',
                    connectionStatus === 'connected' ? 'fa-circle' : 
                    connectionStatus === 'reconnecting' ? 'fa-spinner fa-spin' : 'fa-circle-xmark'
                  ]"
                ></i>
                {{ 
                  connectionStatus === 'connected' ? '在线' : 
                  connectionStatus === 'reconnecting' ? '重连中' : '离线'
                }}
              </span>
            </div>
          </div>
          <div class="header-right">
            <el-button 
              v-if="connectionStatus === 'disconnected'" 
              type="text" 
              @click="retryConnection"
              class="retry-connection-btn"
            >
              <el-icon><Refresh /></el-icon>
              重新连接
            </el-button>
            <el-button type="text" @click="showHistory = !showHistory">
              <el-icon><Clock /></el-icon>
              历史记录
            </el-button>
            <el-button type="text" @click="showSettings = !showSettings">
              <el-icon><Setting /></el-icon>
              设置
            </el-button>
            <el-button type="text" @click="showMediaInput = !showMediaInput">
              <el-icon><Microphone /></el-icon>
              多媒体
            </el-button>
            <el-button type="text" @click="showHealthStatus = !showHealthStatus">
              <el-icon><Monitor /></el-icon>
              健康状态
            </el-button>
          </div>
        </div>
        <div class="message-list" ref="messaggListRef">
          <!-- 连接状态提示 -->
          <div v-if="connectionStatus !== 'connected'" class="connection-status">
            <div v-if="connectionStatus === 'disconnected'" class="status-disconnected">
              <i class="fa-solid fa-wifi-slash"></i>
              <span>网络连接已断开</span>
              <button @click="retryConnection" class="retry-connection-btn">
                <i class="fa-solid fa-refresh"></i> 重新连接
              </button>
            </div>
            <div v-else-if="connectionStatus === 'reconnecting'" class="status-reconnecting">
              <i class="fa-solid fa-spinner fa-spin"></i>
              <span>正在重新连接...</span>
            </div>
          </div>
          
          <!-- 重试状态提示 -->
          <div v-if="isRetrying" class="retry-status">
            <i class="fa-solid fa-clock"></i>
            <span>正在重试 ({{ retryCount }}/{{ maxRetries }})</span>
          </div>
          
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="
              message.isUser ? 'message user-message' : 'message bot-message'
            "
          >
            <!-- 会话图标 -->
            <i
              :class="
                message.isUser
                  ? 'fa-solid fa-user message-icon'
                  : 'fa-solid fa-robot message-icon'
              "
            ></i>
            <!-- 会话内容 -->
            <span>
              <span v-html="filterMessageContent(message.content)"></span>
              <!-- loading -->
              <span
                class="loading-dots"
                v-if="message.isThinking || message.isTyping"
              >
                <span class="dot"></span>
                <span class="dot"></span>
              </span>
            </span>
            
            <!-- 错误信息显示 -->
            <div v-if="!message.isUser && lastError && index === messages.length - 1" class="error-info">
              <div v-if="lastError.type === 'NETWORK_ERROR'" class="error-network">
                <i class="fa-solid fa-exclamation-triangle"></i>
                <span>{{ lastError.userMessage }}</span>
              </div>
              <div v-else-if="lastError.type === 'TIMEOUT_ERROR'" class="error-timeout">
                <i class="fa-solid fa-clock"></i>
                <span>{{ lastError.userMessage }}</span>
              </div>
              <div v-else-if="lastError.type === 'RATE_LIMIT_ERROR'" class="error-rate-limit">
                <i class="fa-solid fa-ban"></i>
                <span>{{ lastError.userMessage }}</span>
              </div>
              <div v-else class="error-general">
                <i class="fa-solid fa-exclamation-circle"></i>
                <span>{{ lastError.userMessage }}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 智能输入助手 -->
        <div class="smart-input-panel">
          <QuickButtons @selectQuestion="handleQuickQuestion" />
          <SymptomTemplate @useTemplate="handleUseTemplate" />
        </div>
        
        <!-- 多媒体输入区域 -->
        <div v-if="showMediaInput" class="media-input-area">
          <MediaInput 
            v-model="inputMessage"
            @voice-result="handleVoiceResult"
            @file-upload="handleFileUpload"
          />
        </div>
        
        <!-- 健康状态检查区域 -->
        <div v-if="showHealthStatus" class="health-status-area">
          <HealthStatus 
            @status-change="handleHealthStatusChange"
            @generate-report="handleGenerateReport"
          />
        </div>
        
        <!-- 历史记录面板 -->
        <div v-if="showHistory" class="history-panel-area">
          <SessionList 
            ref="sessionListRef"
            :currentSessionId="currentSessionId"
            @loadSession="handleLoadSession"
          />
        </div>
        
        <!-- 设置面板 -->
        <div v-if="showSettings" class="settings-panel-area">
          <PersonalSettings 
            ref="personalSettingsRef"
            @settingsChange="handleSettingsChange"
          />
        </div>
        
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            placeholder="请输入消息"
            @keyup.enter="sendMessage"
          ></el-input>
          <el-button 
            type="text" 
            @click="showMediaInput = !showMediaInput"
            :class="{ active: showMediaInput }"
          >
            <el-icon><Microphone /></el-icon>
          </el-button>
          <el-button @click="sendMessage" :disabled="isSending" type="primary"
            >发送</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'
import { ArrowLeft, Clock, Setting, Microphone, Promotion, User, Monitor, Refresh } from '@element-plus/icons-vue'
import QuickButtons from './QuickInput/QuickButtons.vue'
import SymptomTemplate from './QuickInput/SymptomTemplate.vue'
import SessionList from './HistoryPanel/SessionList.vue'
import PersonalSettings from './Settings/PersonalSettings.vue'
import MediaInput from './MediaInput.vue'
import HealthStatus from './HealthStatus.vue'
import { globalErrorHandler, ErrorTypes } from '../utils/errorHandler.js'
import { globalMessageFilter } from '../utils/messageFilter.js'

const router = useRouter()
const messaggListRef = ref()
const sessionListRef = ref()
const personalSettingsRef = ref()
const isSending = ref(false)
const uuid = ref()
const inputMessage = ref('')
const messages = ref([])
const activeTab = ref('chat')
const currentSessionId = ref('')
const showHistory = ref(false)
const showSettings = ref(false)
const showMediaInput = ref(false)
const showHealthStatus = ref(false)

// 连接状态监控
const connectionStatus = ref('connected') // connected, disconnected, reconnecting
const retryCount = ref(0)
const maxRetries = ref(3)
const retryDelay = ref(1000) // 1秒
const lastError = ref(null)
const isRetrying = ref(false)

onMounted(() => {
  initUUID()
  // 移除 setInterval，改用手动滚动
  watch(messages, () => scrollToBottom(), { deep: true })
  // 监听网络状态
  window.addEventListener('online', handleOnline)
  window.addEventListener('offline', handleOffline)
  // 检查初始连接状态
  checkConnectionStatus()
  hello()
})

// 网络状态处理
const handleOnline = () => {
  connectionStatus.value = 'connected'
  retryCount.value = 0
  console.log('网络连接已恢复')
}

const handleOffline = () => {
  connectionStatus.value = 'disconnected'
  console.log('网络连接已断开')
}

// 检查连接状态
const checkConnectionStatus = async () => {
  try {
    const response = await axios.get('/api/health/status', { timeout: 5000 })
    connectionStatus.value = 'connected'
    retryCount.value = 0
  } catch (error) {
    connectionStatus.value = 'disconnected'
    console.warn('服务连接检查失败:', error.message)
  }
}

const scrollToBottom = () => {
  if (messaggListRef.value) {
    messaggListRef.value.scrollTop = messaggListRef.value.scrollHeight
  }
}

const hello = () => {
  sendRequest('你好')
}

const sendMessage = () => {
  if (inputMessage.value.trim()) {
    sendRequest(inputMessage.value.trim())
    inputMessage.value = ''
  }
}

const sendRequest = async (message, isRetry = false) => {
  // 检查网络连接状态
  if (connectionStatus.value === 'disconnected') {
    showErrorMessage('网络连接已断开，请检查网络后重试')
    return
  }
  
  isSending.value = true
  
  if (!isRetry) {
    const userMsg = {
      isUser: true,
      content: message,
      isTyping: false,
      isThinking: false,
    }
    //第一条默认发送的用户消息"你好"不放入会话列表
    if(messages.value.length > 0){
      messages.value.push(userMsg)
    }

    // 添加机器人加载消息
    const botMsg = {
      isUser: false,
      content: '', // 增量填充
      isTyping: true, // 显示加载动画
      isThinking: false,
    }
    messages.value.push(botMsg)
  }
  
  const lastMsg = messages.value[messages.value.length - 1]
  lastMsg.isTyping = true
  lastMsg.content = ''
  scrollToBottom()

  axios
    .post(
      '/api/xiaozhi/chat',
      { memoryId: uuid.value, message },
      {
        responseType: 'text', // 修复流式请求错误
        adapter: 'xhr', // 确保使用XMLHttpRequest适配器
        onDownloadProgress: (progressEvent) => {
          try {
            // 修复现代浏览器兼容性问题
            let fullText = ''
            
            // 尝试多种方式获取响应数据
            if (progressEvent.event && progressEvent.event.target) {
              // 现代浏览器
              fullText = progressEvent.event.target.response || progressEvent.event.target.responseText || ''
            } else if (progressEvent.currentTarget) {
              // 备用方案
              fullText = progressEvent.currentTarget.response || progressEvent.currentTarget.responseText || ''
            } else if (progressEvent.target) {
              // 另一种备用方案
              fullText = progressEvent.target.response || progressEvent.target.responseText || ''
            }
            
            // 确保获取到的是字符串类型的数据
            if (fullText && typeof fullText === 'string' && fullText.length > lastMsg.content.length) {
              const newText = fullText.substring(lastMsg.content.length)
              if (newText.trim()) {
                lastMsg.content += newText // 增量更新
                scrollToBottom() // 实时滚动
              }
            }
          } catch (error) {
            console.warn('流式响应处理错误:', error)
            // 如果流式处理失败，不影响整体请求
          }
        },
      }
    )
    .then(() => {
      // 流结束后隐藏加载动画
      messages.value.at(-1).isTyping = false
      isSending.value = false
      connectionStatus.value = 'connected'
      retryCount.value = 0
      // 自动保存会话
      saveCurrentSession()
    })
    .catch(async (error) => {
      console.error('流式错误:', error)
      
      // 使用全局错误处理器
       const errorResult = await handleChatError(error, {
         retryCount: retryCount.value,
         maxRetries: maxRetries.value,
         context: 'chat_request'
       })
      
      lastError.value = errorResult
      
      // 如果是可重试的错误且未达到最大重试次数
      if (errorResult.retryable && retryCount.value < maxRetries.value) {
        retryCount.value++
        isRetrying.value = true
        connectionStatus.value = 'reconnecting'
        
        // 显示重试提示
        messages.value.at(-1).content = `连接异常，正在重试 (${retryCount.value}/${maxRetries.value})...`
        
        // 延迟后重试
        setTimeout(() => {
          sendRequest(message, true)
        }, retryDelay.value * retryCount.value)
        
        return
      }
      
      // 重试失败或不可重试的错误
      isRetrying.value = false
      connectionStatus.value = errorResult.connectionStatus || 'disconnected'
      messages.value.at(-1).content = errorResult.userMessage
      messages.value.at(-1).isTyping = false
      isSending.value = false
      
      // 如果是连接错误，提供重试按钮
      if (errorResult.showRetryButton) {
        addRetryButton(message)
      }
    })
}

// 使用全局错误处理器的便捷方法
const handleChatError = async (error, context = {}) => {
  try {
    const errorAnalysis = await globalErrorHandler.handle(error, {
      ...context,
      component: 'ChatWindow',
      action: 'sendRequest'
    })
    
    return {
      message: errorAnalysis.message,
      userMessage: errorAnalysis.userMessage,
      retryable: errorAnalysis.retryable,
      connectionStatus: errorAnalysis.severity === 'high' ? 'disconnected' : 'connected',
      showRetryButton: errorAnalysis.showRetryButton,
      type: errorAnalysis.type,
      severity: errorAnalysis.severity
    }
  } catch (handlerError) {
    console.error('错误处理器异常:', handlerError)
    return {
      message: '系统错误',
      userMessage: '抱歉，系统遇到问题，请稍后重试',
      retryable: false,
      connectionStatus: 'disconnected',
      showRetryButton: true,
      type: ErrorTypes.UNKNOWN_ERROR,
      severity: 'high'
    }
  }
}

// 添加重试按钮
const addRetryButton = (originalMessage) => {
  const retryMsg = {
    isUser: false,
    content: `<div class="retry-container">
      <button class="retry-button" onclick="window.retryLastMessage('${originalMessage}')">
        <i class="fa-solid fa-refresh"></i> 重试
      </button>
    </div>`,
    isTyping: false,
    isThinking: false,
  }
  messages.value.push(retryMsg)
  
  // 全局重试函数
  window.retryLastMessage = (msg) => {
    // 移除重试按钮消息
    messages.value.pop()
    // 重新发送请求
    retryCount.value = 0
    sendRequest(msg)
  }
}

// 显示错误消息
const showErrorMessage = (message) => {
  const errorMsg = {
    isUser: false,
    content: `<div class="error-message">
      <i class="fa-solid fa-exclamation-triangle"></i>
      ${message}
    </div>`,
    isTyping: false,
    isThinking: false,
  }
  messages.value.push(errorMsg)
  scrollToBottom()
}

// 手动重试连接
const retryConnection = async () => {
  connectionStatus.value = 'reconnecting'
  try {
    await checkConnectionStatus()
    if (connectionStatus.value === 'connected') {
      showErrorMessage('连接已恢复')
    }
  } catch (error) {
    showErrorMessage('连接重试失败，请稍后再试')
  }
}

// 初始化 UUID
const initUUID = () => {
  let storedUUID = localStorage.getItem('user_uuid')
  if (!storedUUID) {
    storedUUID = uuidToNumber(uuidv4())
    localStorage.setItem('user_uuid', storedUUID)
  }
  uuid.value = storedUUID
}

const uuidToNumber = (uuid) => {
  let number = 0
  for (let i = 0; i < uuid.length && i < 6; i++) {
    const hexValue = uuid[i]
    number = number * 16 + (parseInt(hexValue, 16) || 0)
  }
  return number % 1000000
}

// 转换特殊字符
const convertStreamOutput = (output) => {
  return output
    .replace(/\n/g, '<br>')
    .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
    .replace(/&/g, '&amp;') // 新增转义，避免 HTML 注入
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
}

// 过滤消息内容，使用全局消息过滤器
 const filterMessageContent = (content) => {
   if (!content || typeof content !== 'string') {
     return content
   }
   
   const filterResult = globalMessageFilter.filter(content, {
     isMedical: true,
     component: 'ChatWindow'
   })
   
   // 如果有警告信息，可以在控制台记录
   if (filterResult.warnings.length > 0) {
     console.warn('消息过滤警告:', filterResult.warnings)
   }
   
   return filterResult.content
 }

const newChat = () => {
  // 这里添加新会话的逻辑
  console.log('开始新会话')
  localStorage.removeItem('user_uuid')
  window.location.reload()
}

// 处理快捷问题选择
const handleQuickQuestion = (question) => {
  inputMessage.value = question
  sendMessage()
}

// 处理症状模板使用
const handleUseTemplate = (template) => {
  inputMessage.value = template
}

// 处理会话加载
const handleLoadSession = (session) => {
  currentSessionId.value = session.id
  messages.value = session.messages || []
  uuid.value = session.memoryId
  scrollToBottom()
}

// 处理设置变更
const handleSettingsChange = (settings) => {
  console.log('设置已更新:', settings)
}

// 保存当前会话
const saveCurrentSession = () => {
  if (messages.value.length > 0 && sessionListRef.value) {
    const sessionData = {
      id: currentSessionId.value || uuid.value,
      title: generateSessionTitle(),
      messages: messages.value,
      memoryId: uuid.value,
      timestamp: Date.now()
    }
    sessionListRef.value.saveSession(sessionData)
    currentSessionId.value = sessionData.id
  }
}

// 生成会话标题
const generateSessionTitle = () => {
  if (messages.value.length > 0) {
    const firstUserMessage = messages.value.find(msg => msg.isUser)
    if (firstUserMessage) {
      return firstUserMessage.content.substring(0, 20) + (firstUserMessage.content.length > 20 ? '...' : '')
    }
  }
  return '新会话 ' + new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 处理语音识别结果
const handleVoiceResult = (text) => {
  inputMessage.value = text
}

// 处理文件上传
const handleFileUpload = (file) => {
  console.log('文件上传:', file)
  // 这里可以添加文件处理逻辑
}

// 处理健康状态变化
const handleHealthStatusChange = (status) => {
  console.log('健康状态更新:', status)
  // 可以根据健康状态提供个性化建议
}

// 处理生成健康报告
const handleGenerateReport = (reportData) => {
  console.log('生成健康报告:', reportData)
  // 将健康报告作为消息发送给AI
  const reportMessage = `请根据以下健康数据为我提供专业建议：\n${JSON.stringify(reportData, null, 2)}`
  sendRequest(reportMessage)
}

</script>
<style scoped>
.app-layout {
  display: flex;
  height: 100vh;
  background-image: url('https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=modern%20hospital%20interior%20background%20clean%20white%20medical%20environment%20with%20soft%20lighting%20professional%20healthcare%20setting&image_size=landscape_16_9');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

.sidebar {
  width: 280px;
  background-color: rgba(244, 244, 249, 0.5);
  padding: 20px;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(5px);
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  margin-top: 10px;
}

.sidebar-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.sidebar-tab-container {
  height: 100%;
}

.sidebar-tab-container :deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow: hidden;
}

.sidebar-tab-container :deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 连接状态样式 */
.connection-status {
  margin: 10px 0;
  padding: 12px;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
}

.status-disconnected {
  background-color: rgba(239, 68, 68, 0.1);
  color: #dc2626;
  border: 1px solid rgba(239, 68, 68, 0.2);
}

.status-reconnecting {
  background-color: rgba(59, 130, 246, 0.1);
  color: #2563eb;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.retry-connection-btn {
  margin-left: 10px;
  padding: 4px 8px;
  background-color: #dc2626;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.retry-connection-btn:hover {
  background-color: #b91c1c;
}

/* 重试状态样式 */
.retry-status {
  margin: 10px 0;
  padding: 8px 12px;
  background-color: rgba(245, 158, 11, 0.1);
  color: #d97706;
  border: 1px solid rgba(245, 158, 11, 0.2);
  border-radius: 6px;
  text-align: center;
  font-size: 13px;
}

/* 错误信息样式 */
.error-info {
  margin-top: 8px;
  padding: 10px;
  border-radius: 6px;
  font-size: 13px;
  border-left: 4px solid;
}

.error-network {
  background-color: rgba(239, 68, 68, 0.1);
  color: #dc2626;
  border-left-color: #dc2626;
}

.error-timeout {
  background-color: rgba(245, 158, 11, 0.1);
  color: #d97706;
  border-left-color: #d97706;
}

.error-rate-limit {
  background-color: rgba(168, 85, 247, 0.1);
  color: #7c3aed;
  border-left-color: #7c3aed;
}

.error-general {
  background-color: rgba(107, 114, 128, 0.1);
  color: #374151;
  border-left-color: #6b7280;
}

.error-info i {
  margin-right: 6px;
}

/* 重试按钮样式 */
.retry-container {
  text-align: center;
  margin: 10px 0;
}

.retry-button {
  padding: 8px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.retry-button:hover {
  background-color: #2563eb;
  transform: translateY(-1px);
}

.retry-button:active {
  transform: translateY(0);
}

/* 错误消息样式 */
.error-message {
  padding: 12px;
  background-color: rgba(239, 68, 68, 0.1);
  color: #dc2626;
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: 6px;
  margin: 8px 0;
}

.error-message i {
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .connection-status,
  .retry-status,
  .error-info {
    margin: 8px 0;
    padding: 8px;
    font-size: 12px;
  }
  
  .retry-connection-btn {
    margin-left: 8px;
    padding: 3px 6px;
    font-size: 11px;
  }
  
  .retry-button {
    padding: 6px 12px;
    font-size: 13px;
  }
}

.new-chat-button {
  width: 100%;
  margin-bottom: 15px;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid rgba(224, 224, 224, 0.5);
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.5);
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(3px);
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  /* align-items: center; */
}

.user-message {
  max-width: 70%;
  background-color: #e1f5fe;
  align-self: flex-end;
  flex-direction: row-reverse;
}

.bot-message {
  max-width: 100%;
  background-color: #f1f8e9;
  align-self: flex-start;
}

.message-icon {
  margin: 0 10px;
  font-size: 1.2em;
}

.loading-dots {
  padding-left: 5px;
}

.dot {
  display: inline-block;
  margin-left: 5px;
  width: 8px;
  height: 8px;
  background-color: #000000;
  border-radius: 50%;
  animation: pulse 1.2s infinite ease-in-out both;
}

.dot:nth-child(2) {
  animation-delay: -0.6s;
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(0.6);
    opacity: 0.4;
  }

  50% {
    transform: scale(1);
    opacity: 1;
  }
}
.smart-input-panel {
  margin-bottom: 15px;
}

.input-container {
  display: flex;
}

.input-container .el-input {
  flex: 1;
  margin-right: 10px;
}

.media-input-area {
  margin-bottom: 15px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(224, 224, 224, 0.5);
  backdrop-filter: blur(3px);
}

.health-status-area {
  margin-bottom: 15px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(224, 224, 224, 0.5);
  backdrop-filter: blur(3px);
}

.input-container .el-button.active {
  background-color: #409eff;
  color: white;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409eff;
  margin-right: 15px;
}

.back-button:hover {
  color: #66b1ff;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  margin-bottom: 15px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(224, 224, 224, 0.3);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.doctor-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #67c23a);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.doctor-info h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.status.online {
  background: #e8f5e8;
  color: #52c41a;
}

.status.offline {
  background: #ffe7e7;
  color: #ff4d4f;
}

.status.reconnecting {
  background: #fff7e6;
  color: #fa8c16;
}

.retry-connection-btn {
  color: #1890ff !important;
  border: 1px solid #1890ff;
  border-radius: 6px;
  padding: 4px 8px;
  margin-right: 8px;
}

.retry-connection-btn:hover {
  background: #e6f7ff;
  border-color: #40a9ff;
}

/* 优化按钮响应速度 - 减少过渡延迟 */
.header-right .el-button {
  transition: none !important; /* 移除Element Plus默认过渡 */
}

.header-right .el-button:hover {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #409eff !important;
  transform: none !important; /* 移除transform动画 */
}

.header-right .el-button:active {
  background-color: rgba(64, 158, 255, 0.2) !important;
  transform: scale(0.98) !important; /* 添加即时点击反馈 */
  transition: transform 0.05s !important; /* 极短的点击反馈动画 */
}

/* 优化重试按钮响应速度 */
.retry-connection-btn {
  color: #1890ff !important;
  border: 1px solid #1890ff;
  border-radius: 6px;
  padding: 4px 8px;
  margin-right: 8px;
  transition: none !important; /* 移除过渡动画 */
}

.retry-connection-btn:active {
  transform: scale(0.95) !important;
  transition: transform 0.05s !important;
}

/* 为所有交互按钮添加快速响应样式 */
.el-button--text {
  transition: none !important;
}

.el-button--text:hover {
  background-color: rgba(64, 158, 255, 0.08) !important;
}

.el-button--text:active {
  background-color: rgba(64, 158, 255, 0.15) !important;
  transform: scale(0.97) !important;
  transition: transform 0.05s !important;
}

/* 优化输入区域按钮 */
.input-container .el-button {
  transition: none !important;
}

.input-container .el-button:active {
  transform: scale(0.95) !important;
  transition: transform 0.05s !important;
}

/* 媒体查询，当设备宽度小于等于 768px 时应用以下样式 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px 0 10px 0;
  }
  .app-layout {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    height: auto;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
  }

  .logo-section {
    flex-direction: row;
    align-items: center;
    margin-bottom: 0;
  }

  .logo-text {
    font-size: 16px;
    margin-left: 10px;
    margin-top: 0;
  }

  .logo-section img {
    width: 40px;
    height: 40px;
  }

  .sidebar-tabs {
    display: none;
  }

  .new-chat-button {
    margin-right: 10px;
    width: auto;
    margin-bottom: 0;
  }

  .chat-header {
    padding: 10px 15px;
    margin-bottom: 10px;
  }

  .header-left {
    gap: 10px;
  }

  .header-right {
    gap: 5px;
  }

  .doctor-avatar {
    width: 35px;
    height: 35px;
  }

  .doctor-info h3 {
    font-size: 14px;
  }

  .header-right .el-button {
    padding: 8px;
  }
}

/* 媒体查询，当设备宽度大于 768px 时应用原来的样式 */
@media (min-width: 769px) {
  .main-content {
    padding: 0 0 10px 10px;
  }

  .app-layout {
    display: flex;
    height: 100vh;
    background-image: url('https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=modern%20hospital%20interior%20background%20clean%20white%20medical%20environment%20with%20soft%20lighting%20professional%20healthcare%20setting&image_size=landscape_16_9');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
  }

  .sidebar {
    width: 280px;
    background-color: rgba(244, 244, 249, 0.5);
    padding: 20px;
    display: flex;
    flex-direction: column;
    backdrop-filter: blur(5px);
  }

  .logo-section {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .logo-text {
    font-size: 18px;
    font-weight: bold;
    margin-top: 10px;
  }

  .new-chat-button {
    width: 100%;
    margin-top: 20px;
  }
}
</style>
